package itsec1.cardmanagement;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.net.ServerSocketFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.TrustManagerFactory;

/*
 * card management mockup
 */
public class CardManagement {
	private static final int CUSTOMER_TCP_PORT = 30000;
	private static final String SSL_PROTOCOL = "TLS";
	private static final char[] PASSPHRASE = "cardManager1234"
		.toCharArray();
	private static final String KS_LOCATION = "keys/cardkeys.jks";
	private static final String KS_ALGORITHM = "SunX509";
	private static final String KS_TYPE = "JKS";
	
	private ExecutorService executorService = Executors.newCachedThreadPool();
	private SSLServerSocket customerManagementSocket;
	
	public void start() throws IOException {
		// create socket for communication with customer management
		ServerSocketFactory ssfCustomer = this
				.createServerSocketFactory();
		this.customerManagementSocket = (SSLServerSocket) ssfCustomer
				.createServerSocket(CUSTOMER_TCP_PORT);
		this.customerManagementSocket.setNeedClientAuth(true);
		// start listening for request from customer management
		this.executorService.execute(new CustomerManagementListener(this,
				this.customerManagementSocket));
	}
	
	public void stop() throws IOException {
		this.customerManagementSocket.close();
	}
	
	public ExecutorService getExecutorService() {
		return this.executorService;
	}
	
	private ServerSocketFactory createServerSocketFactory() {
		SSLServerSocketFactory ssf = null;

		try {
			// setting up key manager to do server authentication
			KeyManagerFactory kmf = KeyManagerFactory.getInstance(KS_ALGORITHM);
			KeyStore ks = KeyStore.getInstance(KS_TYPE);
			ks.load(new FileInputStream(KS_LOCATION), PASSPHRASE);
			kmf.init(ks, PASSPHRASE);

			TrustManagerFactory tmf = TrustManagerFactory
					.getInstance(KS_ALGORITHM);
			tmf.init(ks);

			SSLContext ctx = SSLContext.getInstance(SSL_PROTOCOL);
			ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
			ssf = ctx.getServerSocketFactory();
		} catch (Exception e) {
			System.out.println("Error: " + e.getMessage());
			e.printStackTrace();
		}

		return ssf;
	}
}
